<?php 
include('logincheck.php'); 

if (isset($_POST['entryid'])){
	
	function genRandomString() {
		$length = 6; $string = ''; $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; }
		return $string;
	}
	
	$entryid = genRandomString();
	$appointmentDateTime = strtotime($_POST['appointmentdate_3'] . '/' . $_POST['appointmentdate_1'] . '/' . $_POST['appointmentdate_2'] . ' ' .  $_POST['appointmenttimehour'] . ':' . $_POST['appointmenttimeminute'] . ':00 ' . $_POST['appointmenttimepmam']);
	$notifydate = (isset($_POST['send1hour']) ? "1" : "0") . (isset($_POST['send24hours']) ? "1" : "0") . (isset($_POST['send48hours']) ? "1" : "0") . (isset($_POST['send72hours']) ? "1" : "0");
	$entrymodified = "Created";
	
	if (!empty($_POST['entryid'])){
		mysql_query("DELETE FROM notifications WHERE entryid='" . $_POST['entryid'] . "'");
		$entryid = $_POST['entryid'];
		$entrymodified = "Updated";
	}
	
	mysql_query("INSERT INTO notifications (entryid,facebookid,clientnamefirst,clientnamelast,cellnumber,emailaddress,sendsms,sendemail,notifydate,appointmentdate,appointmentbody,format) VALUES ('" . $entryid . "','" . $_SESSION['facebookid'] . "','" . mysql_real_escape_string($_POST['clientnamefirst']) . "','" . mysql_real_escape_string($_POST['clientnamelast']) . "','" . mysql_real_escape_string($_POST['cellnumber']) . "','" . mysql_real_escape_string($_POST['emailaddress']) . "','" . (isset($_POST['sendsms']) ? '1' : '0') . "','" . (isset($_POST['sendemail']) ? '1' : '0') . "','" . mysql_real_escape_string($notifydate) . "','" . mysql_real_escape_string($appointmentDateTime) . "','" . mysql_real_escape_string($_POST['appointmentbody']) . "','" . mysql_real_escape_string($_POST['format']) . "')");

	header('Location: /');

	exit();
}

else if (isset($_GET['delete'])){
	mysql_query("DELETE FROM notifications WHERE entryid='" . $_GET['delete'] . "'");
	header('Location: /');
	exit();
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Create New Appointment Reminder</title>
<link rel="stylesheet" type="text/css" href="form/view.css" media="all">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="form/view.js"></script>
<script type="text/javascript" src="form/calendar.js"></script>
</head>
<body id="main_body">
	
    <div id="content">
    
        <img id="top" src="form/top.png" alt="">
        <div id="form_container">
        
            <h1><a>Create New Appointment Reminder</a></h1>
            <form id="form_216100" class="appnitro"  method="post" action="entry.php">
                        <div class="form_description">
                <h2>Create New Appointment Reminder</h2>
                <p>Enter in the appointment details</p>
            </div>						
                <ul >
                    <li id="li_1" >
                        <label class="description" for="clientnamefirst">Client's first name </label>
                        <div>
                            <input id="clientnamefirst" name="clientnamefirst" class="element text medium" type="text" maxlength="255" value=""/> 
                        </div> 
                        </li>
                    <li id="li_2" >
                        <label class="description" for="clientnamelast">Client's last name </label>
                        <div>
                            <input id="clientnamelast" name="clientnamelast" class="element text medium" type="text" maxlength="255" value=""/> 
                        </div> 
                    </li>
                    <li id="li_3" >
                    	<input id="sendsms" name="sendsms" class="element checkbox" type="checkbox" value="1" checked="checked"/>
                        <label class="inlinechoice" for="sendsms">Send Text Messsage Reminder</label>
                        <div id="sendsmswrapper">
                            <label for="cellnumber" class="description">Client's cell phone number </label>
                            <input id="cellnumber" name="cellnumber" class="element text medium" type="text" maxlength="255" value="" onkeyup="this.value = this.value.replace(/\D+/, '')"/> 
                        </div>
                    </li>
                    <li id="li_4" >
                    	<input id="sendemail" name="sendemail" class="element checkbox" type="checkbox" value="1"/>
                        <label class="inlinechoice" for="sendemail">Send Email Reminder</label>
                        <div id="sendemailwrapper" style="display:none">
                            <label for="emailaddress" class="description">Client's email address </label>
                            <input id="emailaddress" name="emailaddress" class="element text medium" type="text" maxlength="255" value=""/> 
                        </div><p class="guidelines" id="guide_8"><small>Emails are sent from your profile email address.</small></p> 
                    </li>
                    
                    <br style="clear:both"/>
                    
                    <li id="li_5" class="datetimefix">
                        <label class="description" for="appointmentdate_1">Date of appointment </label>
                        <span>
                            <input id="appointmentdate_1" name="appointmentdate_1" class="element text" size="2" maxlength="2" value="" type="text" onkeyup="this.value = this.value.replace (/\D+/, '')"> /
                            <label for="appointmentdate_1">Month</label>
                        </span>
                        <span>
                            <input id="appointmentdate_2" name="appointmentdate_2" class="element text" size="2" maxlength="2" value="" type="text" onkeyup="this.value = this.value.replace (/\D+/, '')"> /
                            <label for="appointmentdate_2">Day</label>
                        </span>
                        <span>
                            <input id="appointmentdate_3" name="appointmentdate_3" class="element text" size="4" maxlength="4" value="" type="text" onkeyup="this.value = this.value.replace (/\D+/, '')">
                            <label for="appointmentdate_3">Year</label>
                        </span>
                    
                        <span id="calendar_6">
                            <img id="cal_img_6" class="datepicker" src="form/calendar.gif" alt="Pick a date.">	
                        </span>
                        <script type="text/javascript">
                            Calendar.setup({
                            inputField	 : "appointmentdate_3",
                            baseField    : "appointmentdate",
                            displayArea  : "calendar_6",
                            button		 : "cal_img_6",
                            ifFormat	 : "%B %e, %Y",
                            onSelect	 : selectDate
                            });
                        </script>
                     
                    </li>
                    
                    <li id="li_6" class="datetimefix">
                        <label class="description" for="appointmenttimehour">Time of appointment </label>
                        <span>
                            <input id="appointmenttimehour" name="appointmenttimehour" class="element text " size="2" type="text" maxlength="2" value="" onkeyup="this.value = this.value.replace (/\D+/, '')"/> : 
                            <label for="appointmenttimehour">Hour</label>
                        </span>
                        <span>
                            <input id="appointmenttimeminute" name="appointmenttimeminute" class="element text " size="2" type="text" maxlength="2" value="" onkeyup="this.value = this.value.replace (/\D+/, '')"/>
                            <label for="appointmenttimeminute">Minute</label>
                        </span>
                        <span>
                            <select class="element select" style="width:4em" id="appointmenttimepmam" name="appointmenttimepmam">
                                <option value="AM" >AM</option>
                                <option value="PM" >PM</option>
                            </select>
                            <label for="appointmenttimepmam">AM/PM</label>
                        </span> 
                    </li>
                    
                    <br style="clear:both"/>
                    
                    <li id="li_7" >
                        <label class="description" for="appointmentbody">What is the appointment? </label>
                        <div>
                            <input id="appointmentbody" name="appointmentbody" class="element text medium" type="text" maxlength="255" value=""/> 
                        </div><p class="guidelines" id="guide_8"><small>Example: "hair cut appointment"</small></p> 
                    </li>
                    
                    <li id="li_8" >
                        <label class="description">When to send the reminder(s) </label>
                        
                        <span>
                        <input id="send1hour" name="send1hour" class="element checkbox" type="checkbox" value="1" checked="checked" />
                        <label class="choice" for="send1hour">1 hour before appointment</label>
                        <input id="send24hours" name="send24hours" class="element checkbox" type="checkbox" value="1" checked="checked" />
                        <label class="choice" for="send24hours">24 hours (1 day) before appointment</label>
                        <input id="send48hours" name="send48hours" class="element checkbox" type="checkbox" value="1" />
                        <label class="choice" for="send48hours">48 hours (2 days) before appointment</label>
                        <input id="send72hours" name="send72hours" class="element checkbox" type="checkbox" value="1" />
                        <label class="choice" for="send72hours">72 hours (3 days) before appointment</label>
                        
                        </span><p class="guidelines" id="guide_1"><small>Reminders are sent relative to the appointment time.</small></p> 
                    </li>
    
                    <li id="li_9" >
                        <label class="description" for="format">Notification message format </label>
                        <div>
							<textarea id="format" class="element textarea medium" name="format"><?php echo $format; ?></textarea>
                        </div><p class="guidelines" id="guide_3"><small><?php echo $formatvars ?></small></p> 
                    </li>
                                  
                    <li style="border:1px solid #333; background-color:#CCC;margin:17px;width:auto">
                        <div style="color:#000">
                            <div style="font-weight:bold">Preview of the reminder text message:</div>
                            <div id="txtpreview" style="font-style:italic;"></div>
                            <div id="warning" style="color:red;font-weight:bold;display:none;">Warning: text message is over 140 characters and will not send properly.</div>
                        </div>
                    </li>
                    
                    <input type="hidden" id="entryid" name="entryid" value="" />
                         
                    <li class="buttons">                 
                        <input id="saveForm" class="button_text" type="submit" name="submit" value="Create" />
                        <a href="/">Cancel and return to dashboard</a>
                    </li>
                </ul>
            </form>	
        </div>
        <img id="bottom" src="form/bottom.png" alt="">
        
        <script type="text/javascript">
		        
			$('#sendsms').bind('change', function(event){
				if ($(this).is(':checked'))
					$('#sendsmswrapper').show();
				else
					$('#sendsmswrapper').hide();
			});
			$('#sendemail').bind('change', function(event){
				if ($(this).is(':checked'))
					$('#sendemailwrapper').show();
				else
					$('#sendemailwrapper').hide();
			});
		
            <?php if (isset($_GET['edit'])) { 
                $result = mysql_query("SELECT * FROM notifications WHERE entryid='" . $_GET['edit'] . "' LIMIT 1");
                $data = mysql_fetch_assoc($result);
            ?>
                setParams = <?php echo json_encode($data); ?>;
                
                for(var key in setParams){
					$("#" + key + "").val(setParams[key]);
                }
                
                var appointmentTime = new Date(parseInt(setParams['appointmentdate']) * 1000);
                $("#appointmentdate_1").val((appointmentTime.getMonth() + 1));
                $("#appointmentdate_2").val(appointmentTime.getDate());
                $("#appointmentdate_3").val(appointmentTime.getFullYear());
                
                var ampm = "AM";
                var appointmentHourFix = appointmentTime.getHours();
                if (appointmentHourFix > 11){ ampm = "PM"; }
                if (appointmentHourFix > 12){ appointmentHourFix = appointmentHourFix - 12; }
                if (appointmentHourFix == 0){ appointmentHourFix = 12; }
                
                $('#appointmenttimepmam').val(ampm);
                $("#appointmenttimehour").val(appointmentHourFix);
                $("#appointmenttimeminute").val(appointmentTime.getMinutes() < 10 ? ('0' + appointmentTime.getMinutes()) : appointmentTime.getMinutes());
    
                $("#send1hour").prop("checked", setParams['notifydate'][0] == '1' ? true : false);
                $("#send24hours").prop("checked", setParams['notifydate'][1] == '1' ? true : false);
                $("#send48hours").prop("checked", setParams['notifydate'][2] == '1' ? true : false);
                $("#send72hours").prop("checked", setParams['notifydate'][3] == '1' ? true : false);
    			
				$("#sendsms").prop("checked", setParams['sendsms'] == 1 ? true : false).change();
				$("#sendemail").prop("checked", setParams['sendemail'] == 1 ? true : false).change();
				
                $("#saveForm").val('Update');
            
			<?php } else { ?>
				
				$("#format").val('<?php echo addslashes($format); ?>');
			
            <?php } ?>
		
            $('#form_216100').bind('submit', function(event){
                if (
                    $("#clientnamefirst").val().length == 0 ||
                    $("#clientnamelast").val().length == 0 ||
                    $("#appointmentdate_1").val().length == 0 ||
                    $("#appointmentdate_2").val().length == 0 ||
                    $("#appointmentdate_3").val().length == 0 ||
                    $("#appointmenttimehour").val().length == 0 ||
                    $("#appointmenttimeminute").val().length == 0 ||
                    $("#appointmentbody").val().length == 0
                ){
                    alert("Fill out all areas first.");
                    return false;
                }
                if (
                    !$('#send1hour').is(':checked') &&
                    !$('#send24hours').is(':checked') &&
                    !$('#send48hours').is(':checked') &&
                    !$('#send72hours').is(':checked')
                ){
                    alert("Check at least one time to send reminder.");
                    return false;
                }
				if ($('#sendsms').is(':checked') && $("#cellnumber").val().length != 10){
					alert("Cell phone number should be 10 digits long.\n\nFor example: (555) 555-5555 should be entered in as 5555555555");
					return false;
				}
				if ($('#sendemail').is(':checked') && !isValidEmailAddress($("#emailaddress").val())){
					alert("Email address is in an incorrect format. \n\nExample: johnsmith@gmail.com");
					return false;
				}
				if (!$('#sendsms').is(':checked') && !$('#sendemail').is(':checked')){
					alert('You must send an text message, email, or both.');
					return false;
				}
				setTimeout("$('#content').hide();$('#loading').show();", 100);
            });
						
			function dateReady(){
				return (
					$("#appointmentdate_1").val().length != 0 &&
                    $("#appointmentdate_2").val().length != 0 &&
                    $("#appointmentdate_3").val().length != 0 &&
                    $("#appointmenttimehour").val().length != 0 &&
                    $("#appointmenttimeminute").val().length != 0);
			}
        
			var weekday=new Array(7);
			weekday[0]="Sunday";
			weekday[1]="Monday";
			weekday[2]="Tuesday";
			weekday[3]="Wednesday";
			weekday[4]="Thursday";
			weekday[5]="Friday";
			weekday[6]="Saturday";
			
			var monthmap=new Array(13);
			monthmap[0]="January";
			monthmap[1]="February";
			monthmap[2]="March";
			monthmap[3]="April";
			monthmap[4]="May";
			monthmap[5]="June";
			monthmap[6]="July";
			monthmap[7]="August";
			monthmap[8]="September";
			monthmap[9]="October";
			monthmap[10]="November";
			monthmap[11]="December";
		
			function getOrdinal(dateint){
				var datestr = dateint.toString();
				var datestrlengh = datestr.length;
				var ordin = 'th';
				switch(datestr.substr(datestrlengh - 1, 1)){
					case '1': ordin = 'st'; break;
					case '2': ordin = 'nd'; break;
					case '3': ordin = 'rd'; break;
					default: ordin = 'th';
				}
				return ordin;
			}
		
            function updatePreview(){
				var dateIsReady = dateReady();
				var previewDate = dateIsReady ? new Date(
					parseInt($("#appointmentdate_3").val()), 
					parseInt($("#appointmentdate_1").val()) - 1, 
					$("#appointmentdate_2").val(),
					$("#appointmenttimehour").val(),
					$("#appointmenttimeminute").val(),
					0, 0) : '';

				var dateString = dateIsReady ? 
					weekday[previewDate.getDay()]
					+ ", " + monthmap[previewDate.getMonth()]
					+ " " + previewDate.getDate() + getOrdinal(previewDate.getDate())
					+ " at " + previewDate.getHours() + ":" + (previewDate.getMinutes() < 10 ? '0' + previewDate.getMinutes() : previewDate.getMinutes()) + ' ' + $("#appointmenttimepmam").val() : '(enter date & time)';
									
				var previewString = $("#format").val()
					.replace('{client first name}', $("#clientnamefirst").val())
					.replace('{client last name}', $("#clientnamelast").val())
					.replace('{company}', '<?php echo $company; ?>')
					.replace('{appointment}', $("#appointmentbody").val())
					.replace('{date}', dateString)
					.replace('{your name}', '<?php echo $username; ?>');
				
				if (previewString.length > 160){
					$('#warning').show();
				}
				else $('#warning').hide();
				
                $("#txtpreview").html(previewString);
                tick();
            }
            
            function tick(){
                setTimeout("updatePreview();", 250);
            }
            
            tick();
        
        </script>
        
	</div>
    
    <div id="loading" style="display:none">
    	Loading...
    </div>
    
</body>
</html>